
package com.lzx.iteam.util;


import android.content.Context;
import android.graphics.*;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import junit.framework.Assert;

public class ImageUtil {
    static final String TAG = "ImageUtil";
    static float mDensity = 0;
    /** xfermode of create bitmap. */
    private static PorterDuffXfermode mXfermode = null;

    public static Drawable getScaledDrwable(final Context aContext,
            final Drawable aDrawable,
            final int aWidthInDp, final int aHightInDp) {
        Drawable scaledDrawable = null;
        if (aDrawable != null
                && aDrawable instanceof BitmapDrawable) {
            BitmapDrawable bmpDraw = (BitmapDrawable) aDrawable;
            Bitmap bmp = bmpDraw.getBitmap();
            Bitmap scaledBitmap = getScaledBitmap(
                    aContext, bmp, aWidthInDp, aHightInDp);
            scaledDrawable = new BitmapDrawable(
                    aContext.getResources(), scaledBitmap);
        }
        return scaledDrawable;
    }

    public static Bitmap getScaledBitmapDrwable(final Context aContext,
            final int aResourceId,
            final int aWidthInDp, final int aHightInDp) {
        Bitmap scaledBmp = null;
        Bitmap bmp = BitmapFactory.decodeResource(
                aContext.getResources(),
                aResourceId);
        if (bmp != null) {
            scaledBmp = getScaledBitmap(
                    aContext, bmp, aWidthInDp, aHightInDp);
            bmp.recycle();
        }
        return scaledBmp;
    }

    public static Bitmap getScaledBitmap(final Context aContext,
            final Bitmap aBitmap,
            final int aWidthInDp, final int aHightInDp) {
        Bitmap scaledBmp = null;
        getDensity(aContext);
        if (aBitmap != null) {
            int width = (int) (aWidthInDp * mDensity);
            int height = (int) (aHightInDp * mDensity);
            scaledBmp = Bitmap.createScaledBitmap(aBitmap,
                    width, height, true);
        }
        return scaledBmp;
    }
    public static float getDensity(final Context aContext) {
        if (mDensity == 0) {
            WindowManager wm = (WindowManager) aContext.getSystemService(
                    Context.WINDOW_SERVICE);
            DisplayMetrics metrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(metrics);
            mDensity = metrics.density;
        }
        return mDensity;
    }
    /**
     * create round-rect bitmap.
     * @param aSrc the source bitmap.
     * @return created bitmap.
     */
    public static Bitmap createRoundBitmap(final Bitmap aSrc,
            final Canvas aCanvas,
            final Paint aPaint,
            final RectF aBmpRect,
            final float aRound) {
        return createRoundBitmap(aSrc,
                aCanvas,
                aPaint,
                aBmpRect,
                aRound,
                Bitmap.Config.ARGB_4444);
    }

    /**
     * create round-rect bitmap.
     * @param aSrc the source bitmap.
     * @return created bitmap.
     */
    public static Bitmap createRoundBitmap(final Bitmap aSrc,
            final Canvas aCanvas,
            final Paint aPaint,
            final RectF aBmpRect,
            final float aRound,
            final Bitmap.Config aConfig) {
        if (mXfermode == null) {
            mXfermode = new PorterDuffXfermode(Mode.SRC_IN);
        }
        float x = aSrc.getWidth();
        float y = aSrc.getHeight();
        Bitmap dst = Bitmap.createBitmap(
                (int) x, (int) y, aConfig);
        aCanvas.setBitmap(dst);
        aPaint.setXfermode(null);
        aCanvas.drawRoundRect(aBmpRect, aRound, aRound, aPaint);
        aPaint.setXfermode(mXfermode);
        aCanvas.drawBitmap(aSrc, 0, 0, aPaint);
        return dst;
    }
    private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440;

    public static Bitmap extractThumbNail(final String path, final int height, final int width, final boolean crop) {
        Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0);

        BitmapFactory.Options options = new BitmapFactory.Options();

        try {
            options.inJustDecodeBounds = true;
            Bitmap tmp = BitmapFactory.decodeFile(path, options);
            if (tmp != null) {
                tmp.recycle();
                tmp = null;
            }

            Log.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop);
            final double beY = options.outHeight * 1.0 / height;
            final double beX = options.outWidth * 1.0 / width;
            Log.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY);
            options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY));
            if (options.inSampleSize <= 1) {
                options.inSampleSize = 1;
            }

            // NOTE: out of memory error
            while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) {
                options.inSampleSize++;
            }

            int newHeight = height;
            int newWidth = width;
            if (crop) {
                if (beY > beX) {
                    newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
                } else {
                    newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
                }
            } else {
                if (beY < beX) {
                    newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
                } else {
                    newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
                }
            }

            options.inJustDecodeBounds = false;

            Log.i(TAG, "bitmap required size=" + newWidth + "x" + newHeight + ", orig=" + options.outWidth + "x" + options.outHeight + ", sample=" + options.inSampleSize);
            Bitmap bm = BitmapFactory.decodeFile(path, options);
            if (bm == null) {
                Log.e(TAG, "bitmap decode failed");
                return null;
            }

            Log.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
            final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
            if (scale != null) {
                bm.recycle();
                bm = scale;
            }

            if (crop) {
                final Bitmap cropped = Bitmap.createBitmap(bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1, width, height);
                if (cropped == null) {
                    return bm;
                }

                bm.recycle();
                bm = cropped;
                Log.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
            }
            return bm;

        } catch (final OutOfMemoryError e) {
            Log.e(TAG, "decode bitmap failed: " + e.getMessage());
            options = null;
        }

        return null;
    }

    /**
     * 改变原有图片颜色，返回一个新的bitmap
     * @param mBitmap 原始bitmap
     * @param mColor 要变成的颜色
     * @return 变色后的bitmap
     */
    public static Bitmap getAlphaBitmap(Bitmap mBitmap,int mColor) {
        //根据原图创建一张新的同样大小的bitmap
        Bitmap mAlphaBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        //根据新的bitmaop创建一块画布
        Canvas mCanvas = new Canvas(mAlphaBitmap);
        //创建画笔对象
        Paint mPaint = new Paint();
        //设置画笔对象的颜色
        mPaint.setColor(mColor);
        //根据原始bitmap获取一个新的bitmap，只保留alpha信息
        Bitmap alphaBitmap = mBitmap.extractAlpha();
        //绘制alphabitmap
        mCanvas.drawBitmap(alphaBitmap, 0, 0, mPaint);
        return mAlphaBitmap;
    }

    /**
     * 生成圆形图片
     * @param bitmap
     * @return
     */
    public static Bitmap createRoundBitmap(Bitmap bitmap){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap output;
        try {
            output = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_4444);
        }catch (OutOfMemoryError e){
            output = Bitmap.createBitmap(120,120, Bitmap.Config.ARGB_4444);
        }

        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = bitmap.getWidth() / 2;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /**
     * 生成圆角图片
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_4444);
            Canvas canvas = new Canvas(output);
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight()));
            final float roundPx = 14;
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(Color.BLACK);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

            final Rect src = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());

            canvas.drawBitmap(bitmap, src, rect, paint);
            return output;
        } catch (Exception e) {
            return bitmap;
        }
    }

    public static Bitmap getBitmapFromView(View view) {
        Bitmap bitmap = null;
        try {
            view.buildDrawingCache();
            bitmap = view.getDrawingCache();
            Bitmap overlay = Bitmap.createBitmap(
                    (int) (view.getMeasuredWidth()),
                    (int) (view.getMeasuredHeight()),
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(overlay);
            Paint paint = new Paint();
            paint.setFlags(Paint.FILTER_BITMAP_FLAG);
            canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
                    | Paint.FILTER_BITMAP_FLAG));
            canvas.drawBitmap(bitmap, 0, 0, paint);
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }
        return bitmap;
    }

}
